﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using StoreClientModuleEx;
using StoreClientModule;
using UnityCore;

namespace MBBStoreClient
{
    public partial class frmStockManager : Form
    {
        StockManager sm = new StockManager();
        Threader t = new Threader();
        StockManagerType[] smt = new StockManagerType[1];

        string lastSearch = "";
        int cPage = 0;
        float tmpQty = 0f;
        public frmStockManager()
        {
            InitializeComponent();

            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);
            sm.ProcessCompleted += new UnityCore.CoreHandler(sm_ProcessCompleted);
            sm.ProcessError += new UnityCore.CoreHandler(sm_ProcessError);

            btnAdd.Click += new EventHandler(btnAdd_Click);
            chkRetail.CheckedChanged += new EventHandler(chkRetail_CheckedChanged);
            
            //txtBarcode.KeyUp += new KeyEventHandler(txtBarcode_KeyUp);
            txtBarcode.KeyPress += new KeyPressEventHandler(txtBarcode_KeyPress);
            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);
            btnNext.Click += new EventHandler(btnNext_Click);
            btnPrev.Click += new EventHandler(btnPrev_Click);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            btnCopy.Click += new EventHandler(btnCopy_Click);
            chkAddMode.CheckedChanged += new EventHandler(chkAddMode_CheckedChanged);
            grdLog.DoubleClick += new EventHandler(grdLog_DoubleClick);
        }

        void grdLog_DoubleClick(object sender, EventArgs e)
        {
            if (grdLog.SelectedRows.Count == 1) Clipboard.SetText(grdLog.SelectedRows[0].Cells[0].Value.ToString());
            txtBarcode.Text = Clipboard.GetText();
            txtBarcode.Focus();
            txtBarcode.SelectionStart = txtBarcode.Text.Length;
        }

        void chkAddMode_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAddMode.CheckState == CheckState.Checked)
            {
                btnAdd.Text = "Add";
                btnAdd.BackColor = Color.Green;
                txtBarcode.BackColor = Color.Green;
                txtQty.BackColor = Color.Green;
            }
            else
            {
                btnAdd.Text = "Deduct";
                btnAdd.BackColor = Color.Red;
                txtBarcode.BackColor = Color.Red;
                txtQty.BackColor = Color.Red;
            }
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            btnAdd.Enabled = false;
            sm.GetAutoBarcode(txtBarcode.Text);
        }

        void btnCopy_Click(object sender, EventArgs e)
        {
            if (grdLog.SelectedRows.Count == 1) Clipboard.SetText(grdLog.SelectedRows[0].Cells[0].Value.ToString());
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            ControlState(false);
            lastSearch = txtSearch.Text;
            cPage = 1;
            StockManagerType smt = new StockManagerType() { fBarcode = lastSearch, fQty = (float)cPage };
            if (radWhole.Checked) smt.fID = 0; else smt.fID = 1;
            sm.GetStockInfo(smt);
        }

        void txtBarcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnAdd.Enabled = false;
                sm.GetAutoBarcode(txtBarcode.Text);
            }
        }

        void btnPrev_Click(object sender, EventArgs e)
        {
            cPage--;
            StockManagerType smt = new StockManagerType() { fBarcode = lastSearch, fQty = (float)cPage };
            sm.GetStockInfo(smt);
        }
        void btnNext_Click(object sender, EventArgs e)
        {
            cPage++;
            StockManagerType smt = new StockManagerType() { fBarcode = lastSearch, fQty = (float)cPage };
            sm.GetStockInfo(smt);
        }
        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                ControlState(false);
                lastSearch = txtSearch.Text;
                cPage = 1;
                StockManagerType smt = new StockManagerType() { fBarcode = lastSearch, fQty = (float)cPage };
                if (radWhole.Checked) smt.fID = 0; else smt.fID = 1;
                sm.GetStockInfo(smt);
            }
        }

        void chkRetail_CheckedChanged(object sender, EventArgs e)
        {
            if (chkRetail.Checked) txtUnit.Enabled = true; else txtUnit.Enabled = false;
        }
        void Add_Stock(object sender, EventArgs e)
        {
            bool isValid = true;
            StockManagerType smt = new StockManagerType() { fBarcode = txtBarcode.Text, fUnit = txtUnit.Text, fQty = (float)txtQty.Value, fDescription = FindDescription(txtBarcode.Text) };
            if (smt.fDescription == "") isValid = false;
            if (smt.fQty == 0) isValid = false;
            if (smt.fBarcode == "") isValid = false;
            if (chkRetail.Checked)
            {
                if (smt.fUnit == "") isValid = false;
            }
            if (isValid)
            {
                ControlState(false);
                
                if (!chkAddMode.Checked)
                {
                    smt.fQty *= -1;
                }
                tmpQty = smt.fQty;
                if (chkRetail.Checked)
                {
                    sm.AddStockRetail(new StockManagerType[]{smt});
                }
                else
                {
                    sm.AddStockWhole(new StockManagerType[] { smt });
                }
            }
            else
            {
                MessageBox.Show("Invalid inputs detected!", "Add Stock", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void sm_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(pcode, msg);
                ControlState(true);
            });
        }
        void sm_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetAutoUnit":
                        txtUnit.Items.Clear();
                        txtUnit.Items.AddRange(sm.UnitList);
                        ControlState(true);
                        break;
                    case "GetAutoBarcode":
                        //Removed these codes because the control was changed from combobox into textbox. As per request by sir Nelson.
                        //txtBarcode.Items.Clear();
                        //txtBarcode.Items.AddRange(sm.BarcodeList);
                        txtBarcode.SelectionStart = txtBarcode.Text.Length;
                        btnAdd.Enabled = true;
                        Add_Stock(null, null);
                        break;
                    case "AddStockRetail":
                    case "AddStockWhole":
                        string unit = txtUnit.Text;
                        if(!chkRetail.Checked) unit = "PCS";
                        
                        StockManagerType smtlog = new StockManagerType() { fUser = Common.Username, fBarcode = txtBarcode.Text, fDate = DateTime.Now.ToString(), fQty = tmpQty, fUnit = unit };
                        sm.AddLog(smtlog);
                        if(chkAddMode.Checked)
                            lstAddDetail.Items.Add("Added " + txtQty.Value + " " + unit + " of " + FindDescription(txtBarcode.Text));
                        else
                            lstAddDetail.Items.Add("Deducted " + txtQty.Value + " " + unit + " of " + FindDescription(txtBarcode.Text));
                        break;        
                    case "AddLog":
                        txtBarcode.Text = "";
                        ControlState(true);
                        txtBarcode.Focus();
                        break;
                    case "GetStockInfo":
                        grdLog.DataSource = sm.StockTable;

                        grdLog.Columns[0].HeaderText = "Barcode";
                        grdLog.Columns[1].HeaderText = "Description";
                        grdLog.Columns[2].HeaderText = "Whole Stock";
                        grdLog.Columns[3].HeaderText = "Retail Stock";
                        grdLog.Columns[4].HeaderText = "PCode";
                        if (sm.StockTable.Rows.Count == 50)
                        {
                            if (cPage != 1)
                            {
                                btnNext.Enabled = true;
                                btnPrev.Enabled = true;
                            }
                            else
                            {
                                btnNext.Enabled = true;
                                btnPrev.Enabled = false;
                            }
                        }
                        else
                        {
                            if (cPage != 1)
                            {
                                btnNext.Enabled = false;
                                btnPrev.Enabled = true;
                            }
                            else
                            {
                                btnNext.Enabled = false;
                                btnPrev.Enabled = false;
                            }
                        }
                        lblPageNum.Text = cPage.ToString();
                        ControlState(true);
                        break;
                }
            });

        }
        string FindDescription(string str)
        {
            string desc = "";
            try
            {
                for (int i = 0; i < sm.BarcodeList.Length; i++)
                {
                    if (sm.BarcodeList[i].ToString().Equals(str))
                    {
                        desc = sm.DescriptionList[i].ToString();
                        break;
                    }
                }
            }
            catch (Exception ex) { }
            return desc;
        }
        void ControlState(bool state)
        {
            pnlDetail.Enabled = state;
            lstAddDetail.Enabled = state;
            pnlStocks.Enabled = state;
            if (state)
            {
                pnlMsg.Visible = false;
            }
            else
            {
                pnlMsg.Visible = true;
            }
        }



        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlForm.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlForm; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            txtQty.Value = 1;
            grdLog.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            radWhole.Checked = true;
            ControlState(false);
            sm.GetAutoUnit();
        }
    }
}
